/**
 * @BaseHttpClient.java  COPYRIGHT xiaojian
 * 
 * Created on 2017年2月20日 上午10:37:14
 */
package xj.toolkit.benchmark.mockclient;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.io.ByteStreams;

import xj.toolkit.util.IdentifierFactory;
import xj.toolkit.util.UUIDIdentifier;

/**
 * @author <a href="mailto:cxj2000@gmail.com">xiaojian.cao</a>
 *
 */
public class BaseHttpClient {

	private static final Logger logger = LoggerFactory
			.getLogger(BaseHttpClient.class);


	public String post(String url, byte[] body, String contentType, int msgCode)
			throws Exception {
		HttpURLConnection conn = (HttpURLConnection) new URI(url).toURL()
				.openConnection();

		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setRequestProperty("Content-Type", contentType);
		conn.setRequestProperty("Msg", "" + msgCode);
		conn.setRequestProperty("uuid", IdentifierFactory.gerIdString(new UUIDIdentifier()));
		conn.setRequestProperty("V", "" + 0);
		conn.getOutputStream().write(body);

		contentType = conn.getContentType();
		String encoding = "utf-8";
		if (contentType != null && contentType.indexOf("charset=") > 0) {
			encoding = contentType.split("charset=")[1];
		}

		InputStream is = conn.getInputStream();
		byte[] resp = ByteStreams.toByteArray(is);
		conn.disconnect();
		return new String(resp, encoding);
	}

}
